package com.dog.basics.service.sys.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.sys.SysDeptAddDto;
import com.dog.basics.bean.dto.admin.sys.SysDeptEditDto;
import com.dog.basics.bean.model.sys.SysDept;
import com.dog.basics.bean.vo.admin.sys.SysDeptChildVo;
import com.dog.basics.dao.sys.SysDeptMapper;
import com.dog.basics.dao.sys.SysRoleDeptMapper;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.sys.ISysDeptService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author guoy
 * @since 2020-03-19
 */
@Service
@AllArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    private final SysDeptMapper sysDeptMapper;
    private final SysRoleDeptMapper sysRoleDeptMapper;

    @Override
    public List<Long> listDeptIdByRoleId(Long roleId) {
        return sysDeptMapper.listDeptIdByRoleId(roleId);
    }

    @Override
    public List<SysDeptChildVo> listChildrenDeptByParentId(Long parentId) {
        return sysDeptMapper.listChildrenDeptByParentId(parentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSysDeptAddDto(SysDeptAddDto sysDeptAddDto) {
        SysDept sysDept = new SysDept();
        BeanUtil.copyProperties(sysDeptAddDto, sysDept);
        sysDept.setCreateTime(DateUtil.currentSeconds());
        sysDept.setCreateBy(SecurityUtils.getSysUser().getUserId());
        return this.save(sysDept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSysDeptEditDto(SysDeptEditDto sysDeptEditDto) {
        SysDept sysDept = this.getById(sysDeptEditDto.getDeptId());
        BeanUtil.copyProperties(sysDeptEditDto, sysDept);
        sysDept.setUpdateTime(DateUtil.currentSeconds());
        sysDept.setUpdateBy(SecurityUtils.getSysUser().getUserId());
        return this.updateById(sysDept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSysDept(Long deptId) {
        //删除部门
        this.removeById(deptId);
        //删除部门与角色关联
        sysRoleDeptMapper.deleteByDeptId(deptId);

    }

}
